package cn.stylefeng.guns.modular.business.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.stylefeng.guns.modular.business.entity.AttendanceRecordRequest;
import cn.stylefeng.guns.modular.business.pojo.AttendanceRecord;
import cn.stylefeng.guns.modular.business.service.AttendanceRecordService;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class AttendanceSchedule {

    private static final int PAGE_SIZE = 100;

    @Resource
    private AttendanceRecordService attendanceRecordService;

    // 定时任务,每天一点执行
    @Scheduled(cron = "0 0 1 * * ?")
    private void configureTasks() {
        // 获取昨天日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        String yesterdayStr = LocalDateTimeUtil.format(yesterday, DatePattern.NORM_DATE_PATTERN);

        AttendanceRecordRequest recordRequest = new AttendanceRecordRequest();
        recordRequest.setAttendanceDay(yesterdayStr);
        recordRequest.setPageSize(PAGE_SIZE);

        // 分页遍历昨天所有的打卡记录
        int pageNo = 1;
        while (true) {
            recordRequest.setPageNo(pageNo);
            PageResult<AttendanceRecord> page = attendanceRecordService.findPage(recordRequest);
            List<AttendanceRecord> rows = page.getRows();
            // 打卡记录为空了，就可以结束了
            if (CollectionUtil.isEmpty(rows)) {
                return;
            }

            // 循环所有打卡记录
            for (AttendanceRecord row : rows) {
                if (row.getStartTime() == null || row.getEndTime() == null) {
                    attendanceRecordService.abnormal(row.getRecordId());
                    continue;
                }
                // 如果上下班时间差小于8个小时，就将打卡记录设置为异常
                if (DateUtil.between(row.getStartTime(), row.getEndTime(), DateUnit.HOUR) < 8) {
                    attendanceRecordService.abnormal(row.getRecordId());
                }
            }

            pageNo++;
        }
    }
}
